package com.pie4cloud.pie.job.executor.utils.netty;

import com.alibaba.fastjson.JSONArray;
import com.pie4cloud.pie.dmz.client.NettyConnManage;
import com.pie4cloud.pie.dmz.entty.TransferInfo;
import com.pie4cloud.pie.dmz.entty.netty.Message;
import com.pie4cloud.pie.dmz.handler.NettyUpDownHandler;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.SynchronousQueue;

@Component
public class NettyUtil {
	@Autowired
	private NettyConnManage nettyConnManage;
	@Autowired
	private NettyUpDownHandler nettyUpDownHandler;


	public Object send(TransferInfo transferInfo) throws InterruptedException, IOException {

		Channel channel = nettyConnManage.chooseChannel();
		if (channel!=null && channel.isActive()) {
			SynchronousQueue<Object> queue = nettyUpDownHandler.sendRequest(transferInfo,channel);
			Object result = queue.take();
			return JSONArray.toJSONString(result);
		}else{
			Message res = new Message();
			res.setCode(-1);
			return JSONArray.toJSONString(res);
		}
	}
}
